package com.zn.opit.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {

    @GetMapping("/download")
    public void download(HttpServletResponse response) {
        String filename = "图片.jpg";
        String path = "img/" + filename; // resources下路径，比如文件位置在：resources/img/图片.jpg
        ClassPathResource classPathResource = new ClassPathResource(path);

        try (FileInputStream fis = new FileInputStream(classPathResource.getFile());
             ServletOutputStream sos = response.getOutputStream()) {
            //设置响应头
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8''"
                    + URLEncoder.encode(filename, "UTF-8"));

            IOUtils.copy(fis, sos);
        } catch (Exception e) {
            throw new RuntimeException("下载失败！");
        }
    }
}
